package com.cat.binaryTree;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/count-nodes-equal-to-average-of-subtree/
 * @create 2025/9/12 20:54
 * @since JDK17
 */

public class Solution24 {
    int ans;
    int[] f(TreeNode root) {
        if (root == null) {
            return new int[]{0, 0};
        }
        int val = root.val, cnt = 1;
        int[] l = f(root.left);
        int[] r = f(root.right);
        val += l[0] + r[0];
        cnt += l[1] + r[1];
        if (val / cnt == root.val) {
            ans++;
        }
        return new int[]{val, cnt};
    }

    public int averageOfSubtree(TreeNode root) {
        f(root);
        return ans;
    }
}
